/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.lettuce.core.dynamic.annotation.Param;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.modules.system.domain.vo.ExercisesetandquestionQueryCriteria;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;

/**
* @author shitou
* @date 2024-04-21
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "习题集题库试题管理")
@RequestMapping("/api/exercisesetandquestion")
public class ExercisesetandquestionController {

    private final ExercisesetandquestionService exercisesetandquestionService;

    private final QuestionService queryService;

    private final QuestionoptionService questionOptionService;

    private final UserquestionlogService userquestionlogService;

    private final UserService userService;

    private final UserexercisesetlogService userexercisesetlogService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
//    @PreAuthorize("@el.check('exercisesetandquestion:list')")
    public void exportExercisesetandquestion(HttpServletResponse response, ExercisesetandquestionQueryCriteria criteria) throws IOException {
        exercisesetandquestionService.download(exercisesetandquestionService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询习题集题库试题")
    @ApiOperation("查询习题集题库试题")
//    @PreAuthorize("@el.check('exercisesetandquestion:list')")
    public ResponseEntity<List<Question>> queryExercisesetandquestion(@Param("criteria") ExercisesetandquestionQueryCriteria criteria){

        Userexercisesetlog userexercisesetlog = new Userexercisesetlog();
        //获取本试卷状态
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userService.getOne(new QueryWrapper<User>().eq("username", currentUserName));
        QueryWrapper userExercisetqueryWrapper = new QueryWrapper<>();
        if(criteria.getTeachChapterId()!=null){
            userExercisetqueryWrapper.eq("teachChapterId",criteria.getTeachChapterId());
        }
        if(criteria.getTeachSubsectionId()!=null){

            userExercisetqueryWrapper.eq("teachSubsectionId",criteria.getTeachSubsectionId());
        }
        userExercisetqueryWrapper.eq("subsectionExerciseSetId",criteria.getSubsectionExerciseSetId());


        if(criteria.getCourseId()!=null){

            userExercisetqueryWrapper.eq("courseId",criteria.getCourseId());
        }
        if(criteria.getExercisesetId()!=null){

            userExercisetqueryWrapper.eq("exerciseSetId",criteria.getExercisesetId());

        }

        if(currentUser.getId()!=null){
            userExercisetqueryWrapper.eq("userId",currentUser.getId());
            userexercisesetlog = userexercisesetlogService.getOne(userExercisetqueryWrapper);
        }
        //获取试题列表
        List<Exercisesetandquestion> list1 = exercisesetandquestionService.queryAll(criteria);

        List<Integer> list2 = new ArrayList<>();
        for(Exercisesetandquestion existetandquestion :list1){
            list2.add(existetandquestion.getQuestionid());
        }

        List<Question> questionList = queryService.queryAllByIds(list2);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.in("questionId",list2);
        List<Questionoption> questionOptionList =  questionOptionService.list(queryWrapper);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("questionId",list2);
        queryWrapper1.in("subsectionExerciseSetId",criteria.getSubsectionExerciseSetId());

        List<Userquestionlog> userquestionlogs =  userquestionlogService.queryUserlist(queryWrapper1);
        for(Question question : questionList){
            List<Questionoption> questionoptions = new ArrayList<>();
            List<Userquestionlog> userquestionlog1s = new ArrayList<>();

            for(Questionoption questionoption:questionOptionList){
                if(Objects.equals(question.getId(), questionoption.getQuestionid())){
                    if(userexercisesetlog!=null && !Objects.equals(userexercisesetlog.getIscomplete(), "1")) {
                        questionoption.setIsTrue(null);
                    }
                    if(question.getType() == 3){
                        if(userexercisesetlog!=null && !Objects.equals(userexercisesetlog.getIscomplete(), "1")) {
                            questionoption.setName(null);
                        }
                        questionoptions.add(questionoption);
                    } else {
                        questionoptions.add(questionoption);
                    }

                }
            }

            for(Userquestionlog userquestionlog :userquestionlogs){
                if(Objects.equals(String.valueOf(question.getId()), String.valueOf(userquestionlog.getQuestionid()))){

                    userquestionlog1s.add(userquestionlog);
                }
            }

            question.setQuestionoptions(questionoptions);


            question.setUserquestionlogs(userquestionlog1s);
            if(userquestionlog1s.size() != 0){
                question.setAnswerArr(userquestionlog1s.get(0).getContent());
            }



        }
        return new ResponseEntity<>(questionList,HttpStatus.OK);
    }
    @GetMapping("/getList")
//    @Log("查询习题集题库试题")
//    @ApiOperation("查询习题集题库试题")
    public ResponseEntity<List<Question>> getList(@Param("exercisesetid") Integer exercisesetid){

        ExercisesetandquestionQueryCriteria criteria = new ExercisesetandquestionQueryCriteria();
        criteria.setExercisesetId(exercisesetid);
        List<Exercisesetandquestion> list1 = exercisesetandquestionService.queryAll(criteria);
        List<Integer> list2 = new ArrayList<>();
        for(Exercisesetandquestion existetandquestion :list1){
            list2.add(existetandquestion.getQuestionid());
        }
        System.out.println("list2"+list2);
        List<Question> questionList = queryService.queryAllByIds(list2);
        System.out.println("list2"+questionList);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.in("questionId",list2);
//        List<Questionoption> questionOptionList =  questionOptionService.list(queryWrapper);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("questionId",list2);


        List<Question> resultList = new ArrayList<>();
        if(!questionList.isEmpty() && questionList!=null){
            for(Question question : questionList){
                List<Questionoption> questionoptions = new ArrayList<>();

                for(Exercisesetandquestion existetandquestion :list1){
                    list2.add(existetandquestion.getQuestionid());
                    if(Objects.equals(String.valueOf(question.getId()), String.valueOf(existetandquestion.getQuestionid()))){

                        question.setScore(existetandquestion.getScore());
                    }
                }

                question.setQuestionoptions(questionoptions);

                resultList.add(question);
            }

        }
//        System.out.println("resultList"+resultList);
        return new ResponseEntity<>(resultList,HttpStatus.OK);
    }

    @PostMapping
    @Log("新增习题集题库试题")
    @ApiOperation("新增习题集题库试题")
//    @PreAuthorize("@el.check('exercisesetandquestion:add')")
    public ResponseEntity<Object> createExercisesetandquestion(@Validated @RequestBody Exercisesetandquestion resources){

        exercisesetandquestionService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PostMapping("/save")
    @Log("新增习题集题库试题")
    @ApiOperation("新增习题集题库试题")
//    @PreAuthorize("@el.check('exercisesetandquestion:add')")
    public ResponseEntity<Object> saveExercisesetandquestion(@Validated @RequestBody List<Exercisesetandquestion> resources){
        if(resources.size()==0){
            return null;
        }
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("exerciseSetId", resources.get(0).getExercisesetid());
        List<Exercisesetandquestion>  list2 =  exercisesetandquestionService.list(queryWrapper);

        List<Integer>  alearyIds = new ArrayList<>();
        for(Exercisesetandquestion exercisesetandquestion1:resources){
            alearyIds.add(exercisesetandquestion1.getQuestionid());
        }

        //记录删除的试题id
        List<Integer> deleteIds = new ArrayList<>();
        for(Exercisesetandquestion exercisesetandquestion1:list2){
            if(!containsElement(alearyIds,exercisesetandquestion1.getQuestionid())){
                deleteIds.add(exercisesetandquestion1.getQuestionid());

            }
        }

        if(!deleteIds.isEmpty()){
            queryWrapper.in("questionId",deleteIds);
            exercisesetandquestionService.remove(queryWrapper);
        }

        //记录更新的试题id
        List<Integer> list3 = new ArrayList<>();


        for(Exercisesetandquestion exercisesetandquestion : resources){
            for(Exercisesetandquestion exercisesetandquestion1:list2){
                if(Objects.equals(String.valueOf(exercisesetandquestion.getExercisesetid()), String.valueOf(exercisesetandquestion1.getExercisesetid()))){
                    if(Objects.equals(String.valueOf(exercisesetandquestion.getQuestionid()), String.valueOf(exercisesetandquestion1.getQuestionid()))){
                        exercisesetandquestion.setId(exercisesetandquestion1.getId());

                        exercisesetandquestionService.update(exercisesetandquestion);
                        list3.add(exercisesetandquestion.getQuestionid());
                    }
                }
            }


        }

        for(Exercisesetandquestion exercisesetandquestion : resources){

            if(!containsElement(list3,exercisesetandquestion.getQuestionid())){

                exercisesetandquestionService.create(exercisesetandquestion);
            }

        }

        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    public boolean containsElement(List<Integer> array, Integer target) {
        for (int i = 0; i < array.size(); i++) {
            if (array.get(i) ==  target) {
                return true;
            }
        }
        return false;
    }
    @PutMapping
    @Log("修改习题集题库试题")
    @ApiOperation("修改习题集题库试题")
//    @PreAuthorize("@el.check('exercisesetandquestion:edit')")
    public ResponseEntity<Object> updateExercisesetandquestion(@Validated @RequestBody Exercisesetandquestion resources){
        exercisesetandquestionService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除习题集题库试题")
    @ApiOperation("删除习题集题库试题")
    @PreAuthorize("@el.check('exercisesetandquestion:del')")
    public ResponseEntity<Object> deleteExercisesetandquestion(@RequestBody List<Integer> ids) {
        exercisesetandquestionService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}